/**
 * Project Name:fire-industry-DM-center
 * File Name:CustomAuthenticationProvider.java
 * Package Name:com.firestone.service.user.impl
 * Date:2018年3月22日上午10:35:13
 *
*/

package com.firestone.service.user.impl;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.DigestUtils;

import com.firestone.core.enums.SystemCodeEnum;

/**
 * @Description: TODO(自定义身份认证验证组件)
 * @author CAIYJ
 * @date 2018年3月22日 上午10:35:13
 */
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public CustomAuthenticationProvider(UserDetailsService userDetailsService,
            BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        UserDetails userDetails = userDetailsService.loadUserByUsername(name);
        if (null != userDetails) {
            String encodePassword = DigestUtils
                    .md5DigestAsHex(password.getBytes());
            if (userDetails.getPassword().equals(encodePassword)) {
                // 这里设置权限和角色
                // 生成令牌 这里令牌里面存入了:name,password,authorities, 当然你也可以放其他内容
                Authentication auth = new UsernamePasswordAuthenticationToken(
                        name, password, userDetails.getAuthorities());
                return auth;
            } else {
                throw new BadCredentialsException(
                        SystemCodeEnum.userpwd_not_exist.getErrorMsg());
            }
        } else {
            throw new UsernameNotFoundException(
                    SystemCodeEnum.userpwd_not_exist.getErrorMsg());
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}
